package com.idea.relax.boot.config;

import com.idea.relax.boot.async.RelaxAsyncProperties;
import com.idea.relax.boot.security.xss.RelaxXssProperties;
import com.idea.relax.boot.security.xss.XssRequestFilter;
import lombok.AllArgsConstructor;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.servlet.DispatcherType;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author: 沉香
 * @date: 2023/4/3
 * @description: 对于异步线程池的配置
 */
@EnableAsync
@AllArgsConstructor
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(RelaxAsyncProperties.class)
public class AsyncConfiguration implements AsyncConfigurer {

	private final RelaxAsyncProperties asyncProperties;

	@Override
	public Executor getAsyncExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		//核心线程数
		executor.setCorePoolSize(asyncProperties.getCorePoolSize());
		//最大线程数
		executor.setMaxPoolSize(asyncProperties.getMaxPoolSize());
		//队列大小
		executor.setQueueCapacity(asyncProperties.getQueueCapacity());
		//线程最大空闲时间
		executor.setKeepAliveSeconds(asyncProperties.getKeepAliveSeconds());
		//线程名称前缀
		executor.setThreadNamePrefix(asyncProperties.getThreadNamePrefix());
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
		// 这一步千万不能忘了，否则报错： java.lang.IllegalStateException: ThreadPoolTaskExecutor not initialized
		executor.initialize();
		return executor;
	}

	@Override
	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
		return new SimpleAsyncUncaughtExceptionHandler();
	}

}
